package com.zxw.java基础.websocket;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;

/**
 * @projectName: util-cloud
 * @package: com.zxw.java基础.websocket
 * @className: WebSocketClient
 * @author: zhangxuewei
 * @description: TODO
 * @date: 2023/10/30 10:00
 * @version: 1.0
 */
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.simp.stomp.*;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;

@SpringBootApplication
public class WebSocketClient {

    public static void main(String[] args) {
        SpringApplication.run(WebSocketClient.class, args);

        String serverUri = "ws://localhost:8000"; // WebSocket服务器地址

        WebSocketStompClient stompClient = new WebSocketStompClient(new StandardWebSocketClient());
        stompClient.setMessageConverter(new StringMessageConverter());

        StompSessionHandler sessionHandler = new StompSessionHandlerAdapter() {
            @Override
            public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
                System.out.println("Connected to server");
                session.send("/your-endpoint", "你好"); // 发送消息
            }
        };

        stompClient.connect(serverUri, sessionHandler);
    }
}
